import {toJS} from "mobx"
import { observer } from 'mobx-react';
import {Table,Icon,Row,Col,Button,Spin} from 'antd'
import {WeaTools,WeaInput,WeaSelect,WeaBrowser,WeaDatePicker,WeaCheckbox,WeaLocaleProvider,WeaError,WeaInputNumber} from 'ecCom'
import equal from 'deep-equal'
import './style/index.css'
const getLabel = WeaLocaleProvider.getLabel;

@observer
class WeaCptTableEdit extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			columns: [],
			datas: [],
			selectedRowKeys: [],
			current: 1,
			showGroup: props.showGroup ? props.showGroup : false
		}
		this.onEdit = this.onEdit.bind(this);
		this.doCopy = this.doCopy.bind(this);
		this.doDelete = this.doDelete.bind(this);
		this.doAdd = this.doAdd.bind(this);
		this.inputRemind = new Array();
		this.browserRemind = new Array();
		this.datePickerRemind = new Array();
		this.checkboxRemind = new Array();
		this.selectRemind = new Array();
	}
	componentDidMount() {
		const { datas = [], columns = [] } = this.props;
		columns.length > 0 && this.setState(datas.length > 0 ? {datas: this.addKeytoDatas(datas),columns} : {columns})
	}

	componentWillReceiveProps(nextProps,nextState) {
		const { columns = [], datas = [],  } = this.props;
		const _columns = nextProps.columns || [];
		const _showGroup = nextProps.showGroup||false;
		const _datas = nextProps.datas || [];
		const _selectedRowKeys = nextState.selectedRowKeys || [];
		!equal(_columns,this.props.columns)&&this.setState({columns: _columns});
		!equal(_showGroup,this.state.showGroup)&&this.setState({showGroup: _showGroup});
		//!equal(_selectedRowKeys,this.state.selectedRowKeys)&&this.setState({selectedRowKeys: _selectedRowKeys});
		if(!equal(_datas,this.state.datas)){
			this.setState({datas: this.addKeytoDatas(_datas)});
		}
	}
	addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
	render() {
		const { datas, showGroup, selectedRowKeys } = this.state;
		const { title, needAdd, needCopy, batchBrowser } = this.props;
		return(
			<div className="wea-cpt-table-edit" >
				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@pu7v6w`} className="wea-title ">
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@f12wsg`} span="18">
                        <div>{title}</div>
                    </Col>
                    { needAdd&&(batchBrowser?
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@kbopjy`} span="6" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
							<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@k94j2r`}
								{...batchBrowser}
								isSingle={false}
								isMultCheckbox={true}
								hasAdvanceSerach={true}
								customized
								onChange={(ids, names, datas)=> this.doBatchAdd(ids, names, datas)}
							>
								<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w084ik`} 
									style={{
										border:'none',padding:'0px',fontSize:'20px',lineHeight:'1',color: '#2db7f5',backgroundColor:'#fff'
									}} 
									type="primary" 
									// title={getLabel(384822,'从字段模板库批量添加字段')}
									size="small" disabled={0} 
									onClick={()=>{}}><span className="icon-coms-Batch-add-hot"/>
                        		</Button>	
							</WeaBrowser>
							<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cx8jul`} type="primary" title='新增' size="small" onClick={this.doAdd}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@233d8j`} type="plus" /></Button>
							<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ujt9su`} type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ig9y3t`} type="minus" /></Button>
							{needCopy && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xltpz4`} type="primary" disabled={!`${selectedRowKeys}`} title='复制' size="small" onClick={this.doCopy} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@gb1epf`} type="copy" /></Button>}
	                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@kf84hk`} type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
	                    </Col>
						:
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lwq7em`} span="6" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
							<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gh0rjs`} type="primary" title='新增' size="small" onClick={this.doAdd}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@gwzg8x`} type="plus" /></Button>
							<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9084h9`} type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ei0oto`} type="minus" /></Button>
							{needCopy && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0c82jf`} type="primary" disabled={!`${selectedRowKeys}`} title='复制' size="small" onClick={this.doCopy} ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@hm5fkp`} type="copy" /></Button>}
	                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@j85qj9`} type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
	                    </Col>)
                    }
                </Row>
				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@1g7lpt`} className="wea-content" style={{display:showGroup ? "block":"none"} }>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@efo2np`}  span={24}>
						<Table ecId={`${this && this.props && this.props.ecId || ''}_Table@ufmumg`} 
							columns={this.getColumns()}
							dataSource={datas}
							pagination={false}
							rowSelection={needAdd ? this.getRowSelection(): false}
						/>
					 </Col>
                </Row>
            </div>
		)
	}
	getColumns(){
		const { columns } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return this.getColRender( _col, text, record, index );
			}
			return _col
		});
		return _columns
	}
	getColRender( _col, text, record, index ){
		const { com,isLink = false,linkKey =[],linkUrl=""} = _col;
		let _com = [];
		com.map(c => {
			if(typeof c.props === 'object'){
				_com.push(c);
			}else{
				const { domkey,viewAttr = 2,  formItemType = 'INPUT', options = [], browserConditionParam = {} ,value,otherParams,label } = c;
				const _type = formItemType.toUpperCase();
				_com.push(
					<span>
						{ _type === 'INPUT' && !isLink && 
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@kdm62i@${domkey[0]}`}
							ref={(ref) => {
								this.inputRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@te6klm@${domkey[0]}`} 
								defaultValue={value || ""} 
								value={record[domkey[0]]} 
								style={{display: 'inline-block'}}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
								viewAttr={viewAttr} 
								{...otherParams}/>
							</WeaError> 
						}
						{ _type === 'INPUTNUMBER' && !isLink && 
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@1uy3ph@${domkey[0]}`}
							ref={(ref) => {
								this.inputRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@xz4i6q@${domkey[0]}`} 
								defaultValue={value || ""} 
								value={record[domkey[0]]} 
								style={{display: 'inline-block'}}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
								viewAttr={viewAttr} 
								min={c.min}
								max={c.max}
								step={c.step}
								precision = {c.precision}/>
							</WeaError> 
						}
						{ _type === 'BROWSER' && !isLink && 
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@du8u02@${domkey[0]}`}
							ref={(ref) => {
								this.browserRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@f954hv@${domkey[0]}`}
								key={new Date()}
								layout={document.body}
								{...browserConditionParam}
								replaceDatas={this.getBrowerDatas(record, domkey[0])}
								style={{width:"85%", display: 'inline-block'}}
								onChange={(ids, names, bDatas) => this.onEdit(record, index, domkey[0], ids, names, bDatas)}
							/>
							</WeaError> 
						}
						{ _type === 'BROWSER' && isLink && 
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@4zwxlc@${domkey[0]}`}
							ref={(ref) => {
								this.browserRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@7kdbfn@${domkey[0]}`} 
							    layout={document.body}
								{...browserConditionParam}
								replaceDatas={this.getBrowerDatas(record, domkey[0])}
								style={{width:"85%", display: 'inline-block'}}
								onChange={(ids, names, bDatas) => this.onLinkEdit(record, index, domkey[0], ids, names, bDatas,linkUrl,linkKey)}
								 /> 
							</WeaError>
						}
						{ _type === 'DATEPICKER' && 
							<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@zo6kpo@${domkey[0]}`}
							ref={(ref) => {
								this.datePickerRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@rj0ge2@${domkey[0]}`}
								value={record[domkey[0]]} 
								style={{display: 'inline-block'}}
								formatPattern={2}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
							</WeaError>
						}
						{ _type === 'CHECKBOX' &&
						  	<WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@a3ew47@${domkey[0]}`}
							  ref={(ref) => {
								  this.checkboxRemind.push(ref);
							  }}
							  error={'"'+label+'"'+getLabel(21423,"未填写")}
							  tipPosition="top"
							  style={{width:"100%"}}
							  >
							<WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@dd6jj7@${domkey[0]}`}
								value={record[domkey[0]]=="1"? true:false} 
								style={{display: 'inline-block'}}
								viewAttr={viewAttr}
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
							</WeaError>
						}
						{ _type === 'SELECT' &&
						    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@iy2q4e@${domkey[0]}`}
							ref={(ref) => {
								this.selectRemind.push(ref);
							}}
							error={'"'+label+'"'+getLabel(21423,"未填写")}
							tipPosition="top"
							style={{width:"100%"}}
							>
							<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@vlmyd0@${domkey[0]}`}
								value={record[domkey[0]]} 
								style={{display: 'inline-block'}}
								options= {options}
								viewAttr={viewAttr}
								hasBorder
								onChange={value => this.onEdit(record, index, domkey[0], value)}
							/>
							</WeaError>
						}
					</span>
				)
			}
		});
		return (
			<div>
				{_com}
			</div>
		)
	}
	getBrowerDatas(record, key){
		let replaceDatas = [];
		if(record[key + 'span'] !== undefined) {
			let keys = record[key].split(',');
			let values = record[key + 'span'].split(',');
			if(keys.length === values.length){
				keys.map((k, i) => {
					replaceDatas.push({id: k, name: values[i]});
				});
			}else{
				//console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
			}
		}
		return replaceDatas
	}
	getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
				typeof this.props.onRowSelect === 'function' && this.props.onRowSelect(sRowKeys);
			}
		}
		return rowSelection
	}
	onEdit(record, index, key, value, names, bDatas){
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
		this.setState({datas: _datas});
		this.onChange(_datas);
	}

	onLinkEdit(record, index, key, value, names, bDatas,linkUrl,linkKey){
		const that = this;
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
		return WeaTools.callApi(linkUrl, 'GET', {id:value}).then(data => {
			linkKey.map(key=>{
				_datas[index][key] = data[key]||"";
			})
			that.setState({datas: _datas});
			that.onChange(_datas);
		});
	}

	doCopy(){
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			datas.map(data => {
				if(data.key == key){
					let _data = {...data};
					_data.key = _datas.length;
					_datas.push(_data)
				}
			})
		});
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doAdd(){
		const { datas, } = this.state;
		const {datas_0} = this.props
		let _datas = [].concat(datas);
		let _data = {...datas[0]};
		_data = datas_0[0];
		//_data.key = _datas.length;
		_datas.push(_data);
		this.setState({datas:  this.addKeytoDatas(_datas)});
		this.onChange(_datas);
	}
	doDelete(){
		this.inputRemind = [];
		this.browserRemind = [];
		this.datePickerRemind = [];
		this.checkboxRemind = [];
		this.selectRemind = [];
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			_datas = _datas.filter(data => data.key !== key)
		});
		_datas = _datas.map((data, i) => {
			let _data = {...data};
			_data.key = i;
			return _data
		})
		this.setState({datas: _datas,selectedRowKeys: []});
		this.onChange(_datas);
		
	}
	onChange(datas){
		const { columns } = this.state;
		let _datas = datas.map((data, i) => {
			let _data = {...data}
			delete _data.key
			return _data
		})
		typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
	}
	showErrors() {
		let boole = true;
		toJS(this.inputRemind).map(c => {
			if (c && c.props && c.props.children && c.props.children.props && (!c.props.children.props.value||c.props.children.props.value==='') && c.props.children.props.value!==0 && c.props.children.props.viewAttr == "3") {
				c.showError();
				boole = false;
			}
		});
		toJS(this.browserRemind).map(c => {
			if(c && c.props && c.props.children && c.props.children.props &&c.props.children.props.replaceDatas&&(c.props.children.props.replaceDatas[0]?!c.props.children.props.replaceDatas[0].id:!c.props.children.props.replaceDatas[0])&&c.props.children.props.viewAttr=="3"){
				c.showError();
				boole =false;
			}
		});
		toJS(this.datePickerRemind).map(c => {
			if (c && c.props && c.props.children && c.props.children.props && (!c.props.children.props.value||c.props.children.props.value==='') && c.props.children.props.viewAttr == "3") {
				c.showError();
				boole = false;
			}
		});
		toJS(this.selectRemind).map(c => {
			if (c && c.props && c.props.children && c.props.children.props && (!c.props.children.props.value||c.props.children.props.value==='') && c.props.children.props.value!==0 && c.props.children.props.viewAttr == "3") {
				c.showError();
				boole = false;
			}
		});
		return boole;
	}
	doBatchAdd(ids, names, bDatas) {
		if(ids!=''){
			const that = this;
			let _ids = ids.split(",");
			let _names = names.split(",");
			const { datas } = this.state;
			const { datas_0, batchBrowser } = this.props;
			const { key,linkKey =[],linkUrl=""} = batchBrowser;
			let _datas = datas;		
			let _data = datas_0[0];
			for(var index = 0; index<_ids.length; index++) {
				let flag = true;
				for(var i=0;i<_datas.length;i++){
					if(_datas[i]['capitalid']==''){
						$.ajax({
								url : linkUrl,
								data: {id:_ids[index]},
								cache : false, 
								async : false,
								type : "GET",
								dataType : 'json',
								success : function(data){
									_datas[i][key] = _ids[index];
									_datas[i][key + 'span'] = _names[index];
									linkKey.map(key=>{
										_datas[i][key] = data[key];
									})
								}
							});
						flag = false;
						break;
					}
				}
				if(flag){
					let temp_data = {..._data};
					$.ajax({
							url : linkUrl,
							data: {id:_ids[index]},
							cache : false, 
							async : false,
							type : "GET",
							dataType : 'json',
							success : function(data){
								temp_data[key] = _ids[index];
								temp_data[key + 'span'] = _names[index];
								linkKey.map(key=>{
									temp_data[key] = data[key];
								})
								_datas.push(temp_data);
							}
						});
				}  
			}
			that.setState({datas:  that.addKeytoDatas(_datas)});
			that.onChange(_datas);
		}
	}
}

export default WeaCptTableEdit;
